package com.leyou.user.interceptor;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.user.config.JwtProperties;
import com.leyou.user.entity.AppInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
@Component
public class PrivilegeInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties prop;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 拦截微服务的请求，验证是否有调用本服务的权限
            String appToken = request.getHeader(prop.getApp().getHeaderName());
            // 解析token
            Payload<AppInfo> payload = JwtUtils.getInfoFromToken(appToken, prop.getPublicKey(), AppInfo.class);
            // 获取targetId
            AppInfo appInfo = payload.getUserInfo();
            List<Long> targetList = appInfo.getTargetList();
            // 如果目标id集合中包含当前用户微服务的id，说明他有访问本微服务的权限
            if(targetList!=null && targetList.contains(prop.getApp().getId())){
                log.info("服务{}正在请求资源:{}", appInfo.getServiceName(), request.getRequestURI());
                return true;
            }
        } catch (Exception e) {
            log.error("服务访问被拒绝,token认证失败，访问的url：{}",request.getRequestURI(), e);
        }
        // 返回false不会往下执行了
        return false;
    }
}
